#include <pebble.h>
#include "netimage.h"

static const unsigned int UPDATE_FREQUENCY = 60; // How often to refresh the display 

static Window *window;
static TextLayer *text_layer;
static BitmapLayer *bitmap_layer;
static unsigned int offset; // Quasi-random offset, so updates don't hit all at once
static char *image_uri = "https://pebblestart9.appspot.com/tpp1.pbi?time=";
static char* time_format = "%Y%j%H%M";

static void window_load(void) {
  window = window_create();
  Layer *window_layer = window_get_root_layer(window);
  offset = (unsigned int)window_layer % UPDATE_FREQUENCY;
  GRect bounds = layer_get_bounds(window_layer);

  text_layer = text_layer_create((GRect) { .origin = { 0, 72 }, .size = { bounds.size.w, 20 } });
  text_layer_set_text(text_layer, "Loading...");
  text_layer_set_text_alignment(text_layer, GTextAlignmentCenter);
  layer_add_child(window_layer, text_layer_get_layer(text_layer));

  bitmap_layer = bitmap_layer_create(bounds);
  layer_add_child(window_layer, bitmap_layer_get_layer(bitmap_layer));
}

static void window_unload(void) {
  text_layer_destroy(text_layer);
  bitmap_layer_destroy(bitmap_layer);
  window_destroy(window);
}

void display_image(GBitmap *image, void* buffer) {
  bitmap_layer_set_bitmap(bitmap_layer, image);
}

static void render_display(struct tm *tick_time) {
  // Add a time field to the request
  // This is unceremoniously discarded by the server; we use it to bust bad caches :)
  char full_uri[64];
  char time_text[16];
  strftime(time_text, sizeof(time_text), time_format, tick_time);
  strcat(full_uri, image_uri);
  strcat(full_uri, time_text);
  netimage_request(full_uri);
}

static void handle_tick(struct tm *tick_time, TimeUnits units_changed) {
  if (tick_time->tm_sec % UPDATE_FREQUENCY == offset) { // The extra modulus also handles leap seconds 
    render_display(tick_time);
  }
}

static void init(void) {
  window_load();
  const bool animated = false;
  window_stack_push(window, animated);

  netimage_initialize(display_image);
  netimage_request(image_uri);
  tick_timer_service_subscribe(SECOND_UNIT, handle_tick);
}

static void deinit(void) {
  tick_timer_service_unsubscribe();
  netimage_deinitialize();
  window_unload();
}

int main(void) {
  init();

  APP_LOG(APP_LOG_LEVEL_DEBUG, "Done initializing, pushed window: %p", window);
  app_event_loop();
  deinit();
}
